#include "Camera.h"

Camera::Camera(float width
			, float height
			, float fov
			, float nearClip
			, float farClip)
:	pos(25.0f, 50.0f, 25.0f),
	up(0.0f, 1.0f, 0.0f),
	target(0.0f,0.0f,0.0f),
	mCameraHeight(50.0f),
	mCameraRotationY(0.0f),
	mCameraRadius(10.0f),
	offsetPos(0.0f,0.0f,0.0f),
	speed(0.1f)
{
	screenWidth = width;
	screenHeight = height;
	this->fov = fov;
	this->nearClip = nearClip;
	this->farClip = farClip;

	OnResetDevice();
}

Camera::~Camera()
{

}

void Camera::UpdateCamera(float dt)
{
	D3DXVECTOR3 inputDirection = D3DXVECTOR3( (gDInput->keyDown(DIK_LEFT)?1:0) + (gDInput->keyDown(DIK_RIGHT)?-1:0)
											, 0
											, (gDInput->keyDown(DIK_UP)?1:0) + (gDInput->keyDown(DIK_DOWN)?-1:0));

	if(gDInput->keyDown(DIK_NUMPADPLUS))
		mCameraHeight += speed;
	if(gDInput->keyDown(DIK_NUMPADMINUS))
		mCameraHeight -= speed;

	mCameraRotationY += gDInput->mouseDX() / 50.0f;
	mCameraRadius += gDInput->mouseDY() / 50.0f;

	if(fabs(mCameraRotationY) >= 2.0f * D3DX_PI)
		mCameraRotationY = 0.0f;

	if(mCameraRadius < 5.0f)
		mCameraRadius = 5.0f;

	offsetPos += inputDirection * speed * dt;
	target += inputDirection * speed * dt;

	BuildViewMtx();
}

void Camera::OnResetDevice()
{
	BuildViewMtx();
	BuildProjMtx();
}

void Camera::BuildProjMtx()
{
	// Creation de la matrice Perspective
	D3DXMatrixPerspectiveFovLH(&mProj, fov
							, screenWidth/screenHeight
							, nearClip, farClip);
}

void Camera::BuildViewMtx()
{
	float x = mCameraRadius * cosf(mCameraRotationY);
	float z = mCameraRadius * sinf(mCameraRotationY);
	
	pos = offsetPos + D3DXVECTOR3(x, mCameraHeight, z);
	
	// Creation de la matrice de View
	D3DXMatrixLookAtLH(&mView, &pos, &target, &up);
	//HR(gd3dDevice->SetTransform(D3DTS_VIEW, &mView));
}